<template>
  <el-dialog
    v-model="dialogVisible"
    title="病历详情"
    width="90%"
    top="5vh"
    class="medical-record-detail-dialog"
    @close="handleClose"
  >
    <div class="medical-record-detail" v-loading="loading">
      <!-- 患者基本信息 -->
      <el-card class="patient-info-card">
        <template #header>
          <div class="card-header">
            <span>患者信息</span>
          </div>
        </template>
        <div class="patient-basic-grid">
          <div class="info-item">
            <label>姓名：</label>
            <span>{{ recordDetail.patient?.patient_name || '-' }}</span>
          </div>
          <div class="info-item">
            <label>性别：</label>
            <span>{{ recordDetail.patient?.gender || '-' }}</span>
          </div>
          <div class="info-item">
            <label>年龄：</label>
            <span>{{ recordDetail.patient?.patient_age || '-' }}岁</span>
          </div>
          <div class="info-item">
            <label>就诊时间：</label>
            <span>{{ formatDateTime(recordDetail.visit_time) }}</span>
          </div>
          <div class="info-item">
            <label>接诊医生：</label>
            <span>{{ recordDetail.doctor_name || '-' }}</span>
          </div>
          <div class="info-item">
            <label>科室：</label>
            <span>{{ recordDetail.department_name || '-' }}</span>
          </div>
        </div>
      </el-card>

      <!-- 主诉与现病史 -->
      <el-card class="complaint-card">
        <template #header>
          <div class="card-header">
            <span>主诉与现病史</span>
          </div>
        </template>
        <div class="complaint-content">
          <div class="complaint-item">
            <label>主诉：</label>
            <div class="content-text">{{ recordDetail.chief_complaint || '无' }}</div>
          </div>
          <div class="complaint-item">
            <label>现病史：</label>
            <div class="content-text">{{ recordDetail.current_illness || '无' }}</div>
          </div>
          <div class="complaint-item">
            <label>既往史：</label>
            <div class="content-text">{{ recordDetail.past_history || '无' }}</div>
          </div>
          <div class="complaint-item">
            <label>过敏史：</label>
            <div class="content-text">{{ recordDetail.allergy_history || '无' }}</div>
          </div>
        </div>
      </el-card>

      <!-- 体格检查 -->
      <el-card class="examination-card" v-if="hasExaminationData">
        <template #header>
          <div class="card-header">
            <span>体格检查</span>
          </div>
        </template>
        <div class="examination-grid">
          <div class="examination-item" v-if="recordDetail.vital_signs">
            <label>生命体征：</label>
            <div class="content-text">{{ recordDetail.vital_signs }}</div>
          </div>
          <div class="examination-item" v-if="recordDetail.physical_exam">
            <label>体格检查：</label>
            <div class="content-text">{{ recordDetail.physical_exam }}</div>
          </div>
        </div>
      </el-card>

      <!-- 辅助检查 -->
      <el-card class="lab-card" v-if="hasLabData">
        <template #header>
          <div class="card-header">
            <span>辅助检查</span>
          </div>
        </template>
        <div class="lab-results">
          <div class="lab-item" v-for="lab in recordDetail.lab_results" :key="lab.id">
            <div class="lab-name">{{ lab.name }}</div>
            <div class="lab-value">{{ lab.value }} {{ lab.unit }}</div>
            <div class="lab-reference">参考范围：{{ lab.reference_range }}</div>
            <el-tag
              :type="getLabResultType(lab.status)"
              size="small"
              class="lab-status"
            >
              {{ lab.status }}
            </el-tag>
          </div>
        </div>
      </el-card>

      <!-- 诊断与治疗 -->
      <el-card class="diagnosis-card">
        <template #header>
          <div class="card-header">
            <span>诊断与治疗</span>
          </div>
        </template>
        <div class="diagnosis-content">          
          <div class="diagnosis-item">
            <label>最终诊断：</label>
            <div class="diagnosis-tags">
              <el-tag
                v-for="diagnosis in recordDetail.diagnoses"
                :key="diagnosis.id"
                type="primary"
                class="diagnosis-tag"
              >
                {{ diagnosis.name }}
              </el-tag>
              <el-tag
                v-if="recordDetail.current_diagnosis"
                type="primary"
                class="diagnosis-tag"
              >
                {{ recordDetail.current_diagnosis || '无' }}
              </el-tag>
            </div>            
          </div>
          <div class="treatment-item" v-if="recordDetail.treatment_plan">
            <label>治疗方案：</label>
            <div class="content-text">{{ recordDetail.treatment_plan }}</div>
          </div>
          <div class="prescription-item" v-if="hasPrescriptions">
            <label>处方药品：</label>
            <div class="prescription-list">
              <div
                v-for="med in recordDetail.prescriptions"
                :key="med.id"
                class="prescription-item"
              >
                <div class="med-name">{{ med.name }}</div>
                <div class="med-dosage">{{ med.dosage }}</div>
                <div class="med-frequency">{{ med.frequency }}</div>
                <div class="med-duration">{{ med.duration }}</div>
              </div>
            </div>
          </div>
          <div class="advice-item" v-if="recordDetail.medical_advice">
            <label>医嘱：</label>
            <div class="content-text">{{ recordDetail.medical_advice }}</div>
          </div>
        </div>
      </el-card>

      <!-- 医生签名 -->
      <div class="signature-section">
        <div class="signature-info">
          <div class="doctor-signature">
            <div class="signature-label">医生签名：</div>
            <div class="signature-name">{{ recordDetail.doctor_name }}</div>
          </div>
          <div class="record-time">
            <div class="time-label">记录时间：</div>
            <div class="time-value">{{ formatDateTime(recordDetail.create_time) }}</div>
          </div>
        </div>
      </div>

      <!-- 操作按钮 -->
      <div class="action-buttons">
        <el-button type="primary" @click="handlePrint">
          <el-icon><Printer /></el-icon>
          打印病历
        </el-button>
        <el-button @click="handleEdit" v-if="recordDetail.editable">
          <el-icon><Edit /></el-icon>
          编辑病历
        </el-button>
        <el-button @click="handleClose">
          <el-icon><Close /></el-icon>
          关闭
        </el-button>
      </div>
    </div>
  </el-dialog>
</template>

<script setup>
import { ref, watch, computed } from 'vue'
import { ElMessage } from 'element-plus'
import { Printer, Edit, Close } from '@element-plus/icons-vue'

const props = defineProps({
  modelValue: {
    type: Boolean,
    default: false
  },
  recordId: {
    type: Number,
    default: null
  },
  // 新增：接收从父组件传递的病历记录数据
  recordData: {
    type: Object,
    default: null
  }
})

const emit = defineEmits(['update:modelValue'])

// 响应式数据
const dialogVisible = computed({
  get: () => props.modelValue,
  set: (value) => emit('update:modelValue', value)
})

const loading = ref(false)
const recordDetail = ref({})

// 计算属性
const hasExaminationData = computed(() => {
  return recordDetail.value.vital_signs || recordDetail.value.physical_exam
})

const hasLabData = computed(() => {
  return recordDetail.value.lab_results && recordDetail.value.lab_results.length > 0
})

const hasPrescriptions = computed(() => {
  return recordDetail.value.prescriptions && recordDetail.value.prescriptions.length > 0
})

// 监听记录ID和记录数据变化
watch(() => props.recordId, (newId) => {
  if (newId) {
    loadRecordDetail()
  }
})

// 监听记录数据变化，如果父组件传递了完整数据，直接使用
watch(() => props.recordData, (newData) => {
  if (newData) {
    recordDetail.value = {
      ...newData,
      patient: {
        patient_name: newData.patient_name,
        gender: newData.gender,
        patient_age: newData.patient_age
      }
    }
    loading.value = false
  }
}, { immediate: true })

// 方法
const loadRecordDetail = async () => {
  if (!props.recordId) return
  
  // 如果已经有完整数据，不需要重复加载
  if (props.recordData) {
    recordDetail.value = {
      ...props.recordData,
      patient: {
        patient_name: props.recordData.patient_name,
        gender: props.recordData.gender,
        patient_age: props.recordData.patient_age
      }
    }
    return
  }
  
  loading.value = true
  try {
    // TODO: 如果没有完整数据，调用API获取病历详情
    // const response = await medicalRecordApi.getDetail(props.recordId)
    // recordDetail.value = response.data
    
    // 模拟数据
    await new Promise(resolve => setTimeout(resolve, 600))
    
    recordDetail.value = {
      id: props.recordId,
      patient: {
        patient_name: '李永豪',
        gender: '男',
        patient_age: 35
      },
      visit_time: '2024-03-15 09:30:00',
      doctor_name: '张医生',
      department_name: '内科',
      chief_complaint: '头痛、头晕一周，加重一天',
      current_illness: '患者一周前无明显诱因出现头痛、头晕症状，自行服用止痛药后缓解。昨日症状加重，伴有恶心感。',
      past_history: '高血压病史5年，规律服药控制。',
      allergy_history: '青霉素过敏',
      vital_signs: '体温：36.8℃，脉搏：78次/分，呼吸：18次/分，血压：150/95mmHg',
      physical_exam: '神志清楚，心肺听诊无异常，神经系统检查未见明显异常。',
      lab_results: [
        {
          id: 1,
          name: '血常规',
          value: '正常',
          unit: '',
          reference_range: '-',
          status: '正常'
        },
        {
          id: 2,
          name: '血压',
          value: '150',
          unit: 'mmHg',
          reference_range: '90-140',
          status: '偏高'
        }
      ],
      diagnoses: [
        { id: 1, name: '高血压' },
        { id: 2, name: '紧张性头痛' }
      ],
      current_diagnosis: '高血压，紧张性头痛',
      treatment_plan: '调整降压药剂量，建议休息，避免劳累和情绪激动。',
      prescriptions: [
        {
          id: 1,
          name: '硝苯地平控释片',
          dosage: '30mg',
          frequency: '每日一次',
          duration: '30天'
        },
        {
          id: 2,
          name: '布洛芬缓释胶囊',
          dosage: '0.3g',
          frequency: '必要时服用',
          duration: '7天'
        }
      ],
      medical_advice: '定期监测血压，低盐饮食，适当运动，一周后复查。',
      create_time: '2024-03-15 10:45:00',
      editable: true
    }
  } catch (error) {
    ElMessage.error('获取病历详情失败')
  } finally {
    loading.value = false
  }
}

const handleClose = () => {
  recordDetail.value = {}
}

const handlePrint = () => {
  ElMessage.success('正在打印病历...')
  // TODO: 实现打印功能
}

const handleEdit = () => {
  ElMessage.info('编辑病历功能开发中...')
  // TODO: 跳转到病历编辑页面
}

const getLabResultType = (status) => {
  const typeMap = {
    '正常': 'success',
    '偏高': 'warning',
    '偏低': 'warning',
    '异常': 'danger'
  }
  return typeMap[status] || 'info'
}

const formatDateTime = (dateTimeString) => {
  if (!dateTimeString) return '-'
  return dateTimeString.replace(' ', ' ')
}
</script>

<style lang="scss" scoped>
.medical-record-detail-dialog {
  :deep(.el-dialog__body) {
    max-height: 70vh;
    overflow-y: auto;
  }
}

.medical-record-detail {
  .card-header {
    font-weight: 600;
    color: #303133;
  }
}

.patient-info-card {
  margin-bottom: 16px;
}

.patient-basic-grid {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  gap: 16px;
  
  .info-item {
    display: flex;
    align-items: center;
    
    label {
      font-weight: 500;
      color: #606266;
      min-width: 80px;
      margin-right: 8px;
    }
    
    span {
      color: #303133;
    }
  }
}

.complaint-card,
.examination-card,
.lab-card,
.diagnosis-card {
  margin-bottom: 16px;
}

.complaint-content {
  .complaint-item {
    margin-bottom: 16px;
    
    &:last-child {
      margin-bottom: 0;
    }
    
    label {
      font-weight: 500;
      color: #606266;
      margin-bottom: 8px;
      display: block;
    }
    
    .content-text {
      color: #303133;
      line-height: 1.6;
      background: #f8f9fa;
      padding: 12px;
      border-radius: 4px;
      white-space: pre-wrap;
    }
  }
}

.examination-grid {
  .examination-item {
    margin-bottom: 12px;
    
    &:last-child {
      margin-bottom: 0;
    }
    
    label {
      font-weight: 500;
      color: #606266;
      margin-bottom: 4px;
      display: block;
    }
    
    .content-text {
      color: #303133;
      line-height: 1.5;
    }
  }
}

.lab-results {
  .lab-item {
    display: grid;
    grid-template-columns: 1fr 1fr 2fr auto;
    gap: 12px;
    align-items: center;
    padding: 12px;
    border: 1px solid #ebeef5;
    border-radius: 4px;
    margin-bottom: 8px;
    
    &:last-child {
      margin-bottom: 0;
    }
    
    .lab-name {
      font-weight: 500;
      color: #303133;
    }
    
    .lab-value {
      color: #409eff;
      font-weight: 500;
    }
    
    .lab-reference {
      color: #909399;
      font-size: 12px;
    }
    
    .lab-status {
      justify-self: end;
    }
  }
}

.diagnosis-content {
  .diagnosis-item,
  .treatment-item,
  .prescription-item,
  .advice-item {
    margin-bottom: 16px;
    
    &:last-child {
      margin-bottom: 0;
    }
    
    label {
      font-weight: 500;
      color: #606266;
      margin-bottom: 8px;
      display: block;
    }
  }
  
  .diagnosis-tags {
    display: flex;
    gap: 8px;
    flex-wrap: wrap;
  }
  
  .diagnosis-tag {
    margin-bottom: 4px;
  }
  
  .content-text {
    color: #303133;
    line-height: 1.6;
    background: #f8f9fa;
    padding: 12px;
    border-radius: 4px;
    white-space: pre-wrap;
  }
  
  .prescription-list {
    .prescription-item {
      display: grid;
      grid-template-columns: 2fr 1fr 1fr 1fr;
      gap: 12px;
      padding: 8px 12px;
      border-bottom: 1px solid #f0f0f0;
      
      &:last-child {
        border-bottom: none;
      }
      
      .med-name {
        font-weight: 500;
        color: #303133;
      }
      
      .med-dosage,
      .med-frequency,
      .med-duration {
        color: #606266;
        font-size: 14px;
      }
    }
  }
}

.signature-section {
  display: flex;
  justify-content: flex-end;
  margin: 24px 0;
  padding-top: 16px;
  border-top: 1px solid #ebeef5;
  
  .signature-info {
    display: flex;
    gap: 40px;
    
    .doctor-signature,
    .record-time {
      text-align: center;
      
      .signature-label,
      .time-label {
        font-size: 14px;
        color: #909399;
        margin-bottom: 4px;
      }
      
      .signature-name,
      .time-value {
        font-weight: 500;
        color: #303133;
      }
    }
  }
}

.action-buttons {
  display: flex;
  justify-content: center;
  gap: 12px;
  margin-top: 24px;
  padding-top: 16px;
  border-top: 1px solid #ebeef5;
}

@media print {
  .action-buttons {
    display: none;
  }
}
</style>